// server.cpp
#include "common.hpp"
#include <mutex>
#include <thread>
#include <vector>

class ChatServer {
public:
    ChatServer(int port) : port_(port) {}

    void run() {
        int listen_fd = socket(AF_INET, SOCK_STREAM, 0);
        if (listen_fd == -1) { perror("socket"); exit(1); }

        sockaddr_in addr{};
        addr.sin_family = AF_INET;
        //填INADDR_ANY ,后续无论客户端通过 公网 IP、局域网 IP 还是 127.0.0.1 访问该端口，都能连进来
        addr.sin_addr.s_addr = INADDR_ANY;//INADDR_ANY值为 0.0.0.0
        addr.sin_port = htons(port_);

        if (bind(listen_fd, (sockaddr*)&addr, sizeof(addr)) == -1) {
            perror("bind"); exit(1);
        }
        if (listen(listen_fd, 10) == -1) { perror("listen"); exit(1); }

        std::cout << "Server listening on port " << port_ << " ...\n";

        while (true) {
            sockaddr_in client_addr{};
            socklen_t len = sizeof(client_addr);
            int conn_fd = accept(listen_fd, (sockaddr*)&client_addr, &len);
            if (conn_fd == -1) { perror("accept"); continue; }

            std::thread(&ChatServer::handleClient, this, conn_fd).detach();
        }
    }

private:
    int port_;
    std::vector<int> clients_;
    std::mutex mtx_;

    // void handleClient(int fd) {
    //     char buf[BUF_SIZE];
    //     while (true) {
    //         ssize_t bytes = recv(fd, buf, BUF_SIZE - 1, 0);
    //         if (bytes <= 0) break;        // 断开/出错
    //         buf[bytes] = '\0';
    //         broadcast(buf, fd);
    //     }
    //     close(fd);
    // }
// server.cpp（片段）
void handleClient(int fd) {
    sockaddr_in client_addr{};
    socklen_t len = sizeof(client_addr);
    getpeername(fd, (sockaddr*)&client_addr, &len);

    char ip[INET_ADDRSTRLEN];
    inet_ntop(AF_INET, &client_addr.sin_addr, ip, sizeof(ip));
    std::cout << "[Server] Client " << ip << ":" << ntohs(client_addr.sin_port) << " connected\n";

    char buf[BUF_SIZE];
    while (true) {
        ssize_t n = recv(fd, buf, BUF_SIZE - 1, 0);
        if (n <= 0) break;
        buf[n] = '\0';
        std::cout << "[Server] Received: " << buf << std::endl;
        send(fd, buf, n, 0);          // 回显
    }
    close(fd);
    std::cout << "[Server] Client disconnected\n";
}
    void broadcast(const char* msg, int sender_fd) {
        std::lock_guard<std::mutex> lock(mtx_);
        for (int fd : clients_) {
            if (fd != sender_fd)
                send(fd, msg, strlen(msg), 0);
        }
    }
};

int main() {
    ChatServer server(PORT);
    server.run();
    return 0;
}